using System;

namespace Test.ConsoleProgram.Algorithm.Solution
{
    [TestDescription("算法: 0067. 二进制求和")]
    public class No0067_AddBinary : AbsBaseTestItem
    {
        public override void OnTest()
        {
            Assert.TestExe(AddBinary,
                "11",
                "1",
                "100");
            Assert.TestExe(AddBinary,
                "1010",
                "1011",
                "10101");
        }

        public string AddBinary(string a, string b)
        {
            int alen = a.Length, blen = b.Length;
            int n = Math.Max(alen, blen);
            char[] ans = new char[n];
            int carry = 0;
            const int zeroInt = '0';
            for (int i = 0; i < n; i++)
            {
                carry += i < alen ? a[alen - 1 - i] - zeroInt : 0;
                carry += i < blen ? b[blen - 1 - i] - zeroInt : 0;
                ans[n - 1 - i] = (char)(carry % 2 + zeroInt);
                carry /= 2;
            }
            string result = string.Join("", ans);
            return carry > 0 ? "1" + result : result;
        }
    }
}
